// 云函数入口文件
const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  console.log('activityManager云函数接收到的事件:', event)
  
  const wxContext = cloud.getWXContext()
  const { OPENID } = wxContext
  
  try {
    const { action } = event
    
    // 对于获取活动详情和活动列表，允许所有用户访问，无需管理员权限
    if (action === 'getDetail') {
      return await getActivityDetail(event, OPENID)
    }
    
    if (action === 'getList') {
      return await getActivityList(event, OPENID)
    }
    
    // 其他操作需要验证管理员权限
    const adminCheck = await checkAdminPermission(OPENID)
    if (!adminCheck.isAdmin) {
      return {
        success: false,
        message: '您没有管理员权限',
        code: 'NO_PERMISSION'
      }
    }
    
    switch (action) {
      case 'create':
        return await createActivity(event, OPENID)
      case 'update':
        return await updateActivity(event, OPENID)
      case 'delete':
        return await deleteActivity(event, OPENID)
      case 'toggleStatus':
        return await toggleActivityStatus(event, OPENID)
      case 'uploadCover':
        return await uploadCover(event, OPENID)
      default:
        return {
          success: false,
          message: '未知操作类型'
        }
    }
  } catch (error) {
    console.error('activityManager云函数执行失败:', error)
    return {
      success: false,
      message: '操作失败，请重试',
      error: error.message
    }
  }
}

// 检查管理员权限
async function checkAdminPermission(openId) {
  try {
    const userResult = await db.collection('users').where({
      openId: openId
    }).get()
    
    if (userResult.data.length === 0) {
      return { isAdmin: false }
    }
    
    const userData = userResult.data[0]
    return { isAdmin: userData.isAdmin || false }
  } catch (error) {
    console.error('检查管理员权限失败:', error)
    return { isAdmin: false }
  }
}

// 创建活动
async function createActivity(event, openId) {
  const { activityData } = event
  
  if (!activityData) {
    return {
      success: false,
      message: '缺少活动数据'
    }
  }
  
  // 验证必填字段
  if (!activityData.title) {
    return {
      success: false,
      message: '活动名称不能为空'
    }
  }
  
  const currentTime = new Date()
  
  // 构建活动数据
  const activity = {
    title: activityData.title,
    description: activityData.description || '',
    coverUrl: activityData.coverUrl || '',
    startTime: activityData.startTime ? new Date(activityData.startTime) : null,
    endTime: activityData.endTime ? new Date(activityData.endTime) : null,
    voteLimit: activityData.voteLimit || 1,
    status: activityData.status || 'draft', // draft, ongoing, paused, ended
    creatorId: openId,
    createTime: currentTime,
    updateTime: currentTime,
    participantCount: 0,
    totalVotes: 0
  }
  
  try {
    const result = await db.collection('activities').add({
      data: activity
    })
    
    console.log('创建活动成功:', result._id)
    
    return {
      success: true,
      message: '创建活动成功',
      data: {
        activityId: result._id,
        ...activity
      }
    }
  } catch (error) {
    console.error('创建活动失败:', error)
    return {
      success: false,
      message: '创建活动失败: ' + error.message
    }
  }
}

// 更新活动
async function updateActivity(event, openId) {
  const { activityId, activityData } = event
  
  if (!activityId) {
    return {
      success: false,
      message: '缺少活动ID'
    }
  }
  
  if (!activityData) {
    return {
      success: false,
      message: '缺少活动数据'
    }
  }
  
  try {
    // 检查活动是否存在且有权限编辑
    const activityResult = await db.collection('activities').doc(activityId).get()
    
    if (!activityResult.data) {
      return {
        success: false,
        message: '活动不存在'
      }
    }
    
    const activity = activityResult.data
    
    // 检查是否为创建者（管理员可以编辑所有活动）
    if (activity.creatorId !== openId) {
      // 这里可以添加更严格的权限检查
      console.log('非创建者编辑活动:', openId, '活动创建者:', activity.creatorId)
    }
    
    // 构建更新数据
    const updateData = {
      updateTime: new Date()
    }
    
    if (activityData.title !== undefined) updateData.title = activityData.title
    if (activityData.description !== undefined) updateData.description = activityData.description
    if (activityData.coverUrl !== undefined) updateData.coverUrl = activityData.coverUrl
    if (activityData.startTime !== undefined) updateData.startTime = activityData.startTime ? new Date(activityData.startTime) : null
    if (activityData.endTime !== undefined) updateData.endTime = activityData.endTime ? new Date(activityData.endTime) : null
    if (activityData.voteLimit !== undefined) updateData.voteLimit = activityData.voteLimit
    if (activityData.status !== undefined) updateData.status = activityData.status
    
    await db.collection('activities').doc(activityId).update({
      data: updateData
    })
    
    console.log('更新活动成功:', activityId)
    
    return {
      success: true,
      message: '更新活动成功',
      data: {
        activityId: activityId,
        ...updateData
      }
    }
  } catch (error) {
    console.error('更新活动失败:', error)
    return {
      success: false,
      message: '更新活动失败: ' + error.message
    }
  }
}

// 删除活动
async function deleteActivity(event, openId) {
  const { activityId } = event
  
  if (!activityId) {
    return {
      success: false,
      message: '缺少活动ID'
    }
  }
  
  try {
    // 检查活动是否存在
    const activityResult = await db.collection('activities').doc(activityId).get()
    
    if (!activityResult.data) {
      return {
        success: false,
        message: '活动不存在'
      }
    }
    
    const activity = activityResult.data
    
    // 只能删除草稿状态的活动
    if (activity.status !== 'draft') {
      return {
        success: false,
        message: '只能删除草稿状态的活动'
      }
    }
    
    // 检查是否为创建者
    if (activity.creatorId !== openId) {
      console.log('非创建者删除活动:', openId, '活动创建者:', activity.creatorId)
    }
    
    // 删除活动
    await db.collection('activities').doc(activityId).remove()
    
    // 同时删除相关的候选人数据
    await db.collection('candidates').where({
      activityId: activityId
    }).remove()
    
    console.log('删除活动成功:', activityId)
    
    return {
      success: true,
      message: '删除活动成功'
    }
  } catch (error) {
    console.error('删除活动失败:', error)
    return {
      success: false,
      message: '删除活动失败: ' + error.message
    }
  }
}

// 获取活动列表
async function getActivityList(event, openId) {
  const { status, page = 1, pageSize = 20 } = event
  
  try {
    let query = db.collection('activities')
    
    // 按状态筛选
    if (status && status !== 'all') {
      query = query.where({
        status: status
      })
    }
    
    // 分页查询
    const result = await query
      .orderBy('createTime', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get()
    
    // 处理活动数据，添加状态文本和样式类
    const activities = result.data.map(activity => {
      const now = new Date()
      let statusText = '草稿'
      let statusClass = 'status-draft'
      
      if (activity.status === 'ongoing') {
        if (activity.endTime && now > activity.endTime) {
          statusText = '已结束'
          statusClass = 'status-ended'
        } else {
          statusText = '进行中'
          statusClass = 'status-ongoing'
        }
      } else if (activity.status === 'paused') {
        statusText = '已暂停'
        statusClass = 'status-paused'
      } else if (activity.status === 'ended') {
        statusText = '已结束'
        statusClass = 'status-ended'
      }
      
      // 格式化时间范围
      let timeRange = ''
      if (activity.startTime && activity.endTime) {
        const startDate = new Date(activity.startTime)
        const endDate = new Date(activity.endTime)
        timeRange = `${formatDate(startDate)}-${formatDate(endDate)}`
      }
      
      return {
        ...activity,
        statusText,
        statusClass,
        timeRange
      }
    })
    
    return {
      success: true,
      message: '获取活动列表成功',
      data: {
        activities,
        total: result.data.length,
        page,
        pageSize
      }
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    return {
      success: false,
      message: '获取活动列表失败: ' + error.message
    }
  }
}

// 获取活动详情
async function getActivityDetail(event, openId) {
  const { activityId } = event
  
  if (!activityId) {
    return {
      success: false,
      message: '缺少活动ID'
    }
  }
  
  try {
    const activityResult = await db.collection('activities').doc(activityId).get()
    
    if (!activityResult.data) {
      return {
        success: false,
        message: '活动不存在'
      }
    }
    
    const activity = activityResult.data
    
    // 获取候选人列表
    const candidatesResult = await db.collection('candidates').where({
      activityId: activityId
    }).orderBy('createTime', 'asc').get()
    
    return {
      success: true,
      message: '获取活动详情成功',
      data: {
        activity,
        candidates: candidatesResult.data || []
      }
    }
  } catch (error) {
    console.error('获取活动详情失败:', error)
    return {
      success: false,
      message: '获取活动详情失败: ' + error.message
    }
  }
}

// 切换活动状态（暂停/恢复）
async function toggleActivityStatus(event, openId) {
  const { activityId, status } = event
  
  if (!activityId) {
    return {
      success: false,
      message: '缺少活动ID'
    }
  }
  
  if (!status) {
    return {
      success: false,
      message: '缺少状态参数'
    }
  }
  
  try {
    // 检查活动是否存在
    const activityResult = await db.collection('activities').doc(activityId).get()
    
    if (!activityResult.data) {
      return {
        success: false,
        message: '活动不存在'
      }
    }
    
    const activity = activityResult.data
    
    // 检查是否为创建者
    if (activity.creatorId !== openId) {
      console.log('非创建者操作活动状态:', openId, '活动创建者:', activity.creatorId)
    }
    
    // 更新活动状态
    await db.collection('activities').doc(activityId).update({
      data: {
        status: status,
        updateTime: new Date()
      }
    })
    
    console.log('切换活动状态成功:', activityId, '新状态:', status)
    
    return {
      success: true,
      message: '操作成功',
      data: {
        activityId: activityId,
        status: status
      }
    }
  } catch (error) {
    console.error('切换活动状态失败:', error)
    return {
      success: false,
      message: '操作失败: ' + error.message
    }
  }
}

// 上传活动封面
async function uploadCover(event, openId) {
  const { fileID, activityId } = event
  
  if (!fileID) {
    return {
      success: false,
      message: '缺少文件ID'
    }
  }
  
  try {
    // 如果有活动ID，更新活动的封面URL
    if (activityId) {
      await db.collection('activities').doc(activityId).update({
        data: {
          coverUrl: fileID,
          updateTime: new Date()
        }
      })
    }
    
    return {
      success: true,
      message: '上传封面成功',
      data: {
        coverUrl: fileID
      }
    }
  } catch (error) {
    console.error('上传封面失败:', error)
    return {
      success: false,
      message: '上传封面失败: ' + error.message
    }
  }
}

// 格式化日期
function formatDate(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}.${month}.${day}`
} 